<!--课程与题库-在线课程-编辑直播课-->
<template>
  <div class="form-container">
    <el-card class="box-card">
      <div class="card-header">
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/onlineCourse/liveCourseEdit'}">在线课程</el-breadcrumb-item>
          <el-breadcrumb-item>添加/编辑直播课</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-form :model="form"  ref="baseForm" label-width="120px">
        <div class="head-card">
          <!-- 讲师名称 -->
          <el-form-item label="课程名称：" prop="user_name" class="required-item">
            <el-input
              v-model="form.courseName"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 专业等级 -->
          <el-form-item label="专业等级：" prop="qyxx_type">
            <el-select
              v-model="form.courseLevel"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in zyLevel"
                :key="item.value"
                :label="item.label"
                :value="item.label">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 价格 -->
          <el-form-item label="价格：" prop="user_dev">
            <el-input
              v-model="form.courseSalary"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!--有效期-->
          <el-form-item label="分销分佣">
            <span>用户分享给好友，对方完成购买后，该名用户可获得佣金</span>
            <el-radio-group v-model="form.courseFenyong">
              <el-radio label="0">商品金额比例分佣
                <el-input v-model="form.courseBl" :disabled="form.courseFenyong !='0'"  placeholder="请输入" style="width: 80px"></el-input>%
              </el-radio>
              <el-radio label="1">固定金额分佣
                <el-input v-model="form.gudingfy" :disabled="form.courseFenyong !='1'" placeholder="请输入" style="width: 80px"></el-input>元
              </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 讲师 -->
          <el-form-item label="讲师：" prop="qyxx_type">
            <el-select
              v-model="form.courseTeacher"
              placeholder="请选择"
              style="width: 100%"
              multiple
            >
              <el-option
                v-for="item in teacherList"
                :key="item.bt_code"
                :label="item.bt_name"
                :value="item.bt_code">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 截止购买时间 -->
          <el-form-item label="开播时间：">
            <el-date-picker
              v-model="form.courseStarttime"
              type="date"
              placeholder="选择日期"
              style="width: 637px;">
            </el-date-picker>
          </el-form-item>

          <!-- 退款 -->
          <el-form-item label="退款：" prop="user_dev">
            开播时间<el-input
            v-model="form.courseTkTime"
            placeholder="请输入"
            clearable
            style="width: 100px"
          ></el-input>小时之前可退
          </el-form-item>

          <!-- 截止购买时间 -->
          <el-form-item label="截止购买时间：">
            <el-date-picker
              v-model="form.courseDay"
              type="date"
              placeholder="选择日期"
              style="width: 637px;">
            </el-date-picker>
          </el-form-item>

          <!-- 直接间 -->
          <el-form-item label="直播间：" prop="user_dev">
            <span>微信视频号直播间链接</span>
            <el-input
              v-model="form.onlineUrl"
              placeholder="请输入"
              clearable
            ></el-input>
          </el-form-item>

          <!-- 封面 -->
          <el-form-item label="封面：">
            <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :on-change="changeavart"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseLogo" :src="courseLogo" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="upload-tip">展示于列表和详情页。图片小于1M。
              建议上传 3:4 比例（如750x1000px）的JPG/PNG/WebP格式。</div>
          </el-form-item>

          <!-- banner -->
          <el-form-item label="banner：">
<!--            <div class="demo-image__preview">-->
<!--              <el-image-->
<!--                style="width: 200px; height: 200px"-->
<!--                :src="form.courseBanner"-->
<!--                :preview-src-list="srcList">-->
<!--              </el-image>-->
<!--            </div>-->
            <div>
              <el-upload
                class="avatar-uploader"
                action="#"
                :auto-upload="false"
                :on-change="changeBanner"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="courseBanner" :src="courseBanner" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <div class="upload-tip">展示于主要列表。图片小于2M。
              建议上传 5:2 比例（如800x320px）的JPG/PNG/WebP格式。</div>
          </el-form-item>

          <!-- 讲师介绍 -->
          <el-form-item label="课程介绍：" prop="user_phoneno" >
            <el-input
              v-model="form.courseDetail"
              placeholder="请输入"
              clearable
              type="textarea"
              rows="10"
            ></el-input>
          </el-form-item>
        </div>
        <!--表单操作 -->
        <el-form-item>
          <el-button type="primary" :disabled="isButtonDisabled" @click="saveLiveCourse('0')">保存，并发布</el-button>
          <el-button type="primary" @click="saveLiveCourse('1')">仅保存</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {regjguserfail, createbt, querybtlist, createcbzb, uploadres, updatecbzb, updatecbzbstate} from "../../api/InstitutionApi";
import {defineComponent} from "vue";
import { formatDate } from "../../utils/util"

export default {
  data() {
    return {
      form: {
        courseName:'', ///课程名称
        courseLevel:'', ///专业等级
        courseSalary: '', ///价格
        courseFenyong: '', ///分佣方式，选择哪个
        courseBl:'',   ///分佣比例
        gudingfy: '',  ///分佣金额
        courseTeacher:[], ///讲师
        courseStarttime:'', ////开播时间
        courseTkTime: '', ////退款时间
        courseDay:'',  ///截止购买时间
        onlineUrl:'',  ///直播间链接
        apiImgLogoCode:'', ///存储封面取回来code
        apiImgBannerCode: '', ////存储banner的Code
        courseDetail: '', ///课程描述
      },
      courseLogo:'', ///课程封面baser64
      courseBanner: '', ///banner的baser64
      base64Data: '',
      type: [
        {
          value: '护理',
          label: '护理'
        }, {
          value: '康养',
          label: '康养'
        },
      ],
      // 弹窗存储
      editFormVisible: false,
      unReview:'',
      // 题库
      teacherList: [],
      // 专业等级
      zyLevel: [
        { value: '1', label: '一级' },
        { value: '2', label: '二级' },
        { value: '3', label: '三级' },
        { value: '4', label: '四级' },
        { value: '5', label: '五级' }
      ],
      // 直播课编辑内容
      zbrow: {},
      isEdit: false,
    }
  },
  created() {
    // 对于 path: '/detail/:flowId' 的匹配
    // this.form = this.$route.query.flowid;
    // this.imgPhoto()
    // 调取讲师名字
    this.getTeacher()

    // 直播编辑传数据
    this.zbrow = this.$route.query.zbrow
    console.log('编辑直播：',this.zbrow)
    if (this.zbrow) {
      this.isEdit = true
      this.liveCourseEdit()
    } else {
      this.isEdit = false
    }
  },
  computed: {
    isButtonDisabled() {
      // return this.form.base.cur_status === 2; // 可以扩展其他条件，如 || this.isLoading
    }
  },
  methods: {
    // 调取讲师名字列表
    getTeacher() {
      querybtlist({}).then(res => {
        // this.tableDate = res.data.base_info;
        console.log('讲师列表：', res);
        // this.tableDate = res.data.data.base_info
        this.teacherList = res.data.data.base_info
      })
    },
    // 编辑直播
    liveCourseEdit() {
      this.form.courseCode = this.zbrow.bczb_code ///直播code
      this.form.courseName = this.zbrow.bczb_name //#直播名称
      this.form.courseLevel= this.zbrow.bczb_zylevel//#直播级别
      this.form.courseSalary= this.zbrow.bczb_price//#直播价格
      this.form.courseBl= this.zbrow.bczb_percent//#直播折扣比例
      this.form.gudingfy= this.zbrow.bczb_gdmoney//#固定金额
      this.form.courseTeacher= this.zbrow.bztzb_jscode//#直播讲师
      this.form.courseStarttime= this.zbrow.bczb_starttime//#直播开始时间
      this.form.courseTkTime= this.zbrow.bczb_tuikuanhours//#直播退款时间
      this.form.courseDay= this.zbrow.bczb_buylasttime//#直播截止购买时间
      this.form.onlineUrl= this.zbrow.bczb_urllink//#直播链接
      this.form.apiImgLogoCode= this.zbrow.bczb_logo_uri//#直播logo
      this.form.apiImgBannerCode= this.zbrow.bczb_banner[0].imguri//#直播banner
      this.form.courseDetail= this.zbrow.bczb_desc//#直播简介
      this.form.courseFenyong = this.zbrow.bczb_percent !== '' ? '0' : this.zbrow.bczb_gdmoney !== '' ? '1' : '';
      this.courseLogo = this.zbrow.bczb_logo_url
      this.courseBanner = this.zbrow.bczb_banner[0].url
    },
    disabled() {
      return disabled
    },
    // 仅保存并发布
    saveLiveCourse(index) {
      if(this.isEdit) {
      //   编辑
        updatecbzb({
          "bczbcode":this.form.courseCode, ///直播code
          "bczbname": this.form.courseName, //#直播名称
          "bczbzylevel": this.form.courseLevel,//#直播级别
          "bczbprice": this.form.courseSalary,//#直播价格
          "bczbpercent": this.form.courseBl,//#直播折扣比例
          "bczbgdmoney":this.form.gudingfy,//#固定金额
          "bctzblist":this.form.courseTeacher,//#直播标签列表
          "bczbstarttime": formatDate(this.form.courseStarttime) ,//#直播开始时间
          "bczbtuikuanhours":this.form.courseTkTime,//#直播退款时间
          "bczbbuylasttime": formatDate(this.form.courseDay),//#直播截止购买时间
          "bczburllink": this.form.onlineUrl,//#直播链接
          "bczblogouri": this.form.apiImgLogoCode,//#直播logo
          "bczbbanner": this.form.apiImgBannerCode,//#直播banner
          "bczbdesc": this.form.courseDetail,//#直播简介
        }).then(res =>{
          console.log('编辑',res)
          if(res.msg === '更新直播课程基础信息成功') {
            if(index === '0') {
              this.zbPublic()
            }
            this.$router.push({
              path: '/onlineCourse/teacherLine',
              query: ''
            });
          }


        })
      } else {
      //   添加
      //   console.log('添加：', this.form,formatDate(this.form.courseDay))
        createcbzb({
          "bczbname": this.form.courseName, //#直播名称
          "bczbzylevel": this.form.courseLevel,//#直播级别
          "bczbprice": this.form.courseSalary,//#直播价格
          "bczbpercent": this.form.courseBl,//#直播折扣比例
          "bczbgdmoney":this.form.gudingfy,//#固定金额
          "bctzblist":this.form.courseTeacher,//#直播标签列表
          "bczbstarttime": formatDate(this.form.courseStarttime) ,//#直播开始时间
          "bczbtuikuanhours":this.form.courseTkTime,//#直播退款时间
          "bczbbuylasttime": formatDate(this.form.courseDay),//#直播截止购买时间
          "bczburllink": this.form.onlineUrl,//#直播链接
          "bczblogouri": this.form.apiImgLogoCode,//#直播logo
          "bczbbanner": this.form.apiImgBannerCode,//#直播banner
          "bczbdesc": this.form.courseDetail,//#直播简介
        }).then(res => {
          console.log('创建直播：', res)
          if(index === '0') {
            this.zbPublic()
          }
          this.$router.push({
            path: '/onlineCourse/teacherLine',
            query: ''
          });
        })
      }
    },
    // 发布直播
    zbPublic() {
      updatecbzbstate({
        "bczbcode": this.form.courseCode, //#直播课的code
        "bczbstate":"1", //#直播课程状态，0未发布，1已发布，2已经结束
      }).then(res => {


      })
    },
    // 取消
    teacherCancel() {
      // 跳转页面的三种方式
      // 方式1：通过 path 跳转
      // this.$router.push({
      //   path: `/enterprises/EnEdit/:index`
      // });
      // 方式2：通过 name 跳转（推荐）
      // this.$router.push({
      //   name: 'enedit',
      //   params: { index: index }
      // });

      // 方式3：带查询参数（显示在URL中）
      this.$router.push({
        path: '/teachers/teachers',
        query: ''
      });
    },

    // 头像
    // 头像上传
    // 自定义上传方法
    customUpload(type) {
      uploadres({
        "usercode": localStorage.getItem('usercode'), //#用户标识号
        "rescode": this.base64Data,//#图片资源的base64码
        "restype":"0",//#资源类型，0企业营业执照，1企业logo，2门头照，3企业环境,4个人简介视频
        "resdesc": type  //图片描述"
      }).then(res => {
        console.log('图片上传：',res)
        if(type === 'logo') {
          this.form.apiImgLogoCode = res.data.base_info
        } else  {
          // banner
          this.form.apiImgBannerCode = res.data.base_info
        }
      })
    },

    // 上传前将图片转为base64
    // beforeUpload(file,type) {
    //   console.log('转base64', file);
    //   return new Promise((resolve, reject) => {
    //     const reader = new FileReader();
    //     reader.readAsDataURL(file);
    //     reader.onload = () => {
    //       this.base64Data = btoa(reader.result); // 存储base64数据去掉头部的
    //       if(type === 'logo') {
    //         this.courseLogo = reader.result;
    //       } else {
    //         this.courseBanner = reader.result;
    //       }
    //       // console.log('转base64:',this.base64Data)
    //       resolve();
    //       this.customUpload(type)
    //     };
    //     reader.onerror = error => reject(error);
    //   });
    // },

    beforeUpload(file,type) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          // 方法1：直接使用完整的DataURL（推荐）
          if(type === 'logo') { // 带前缀的完整Base64，可直接用于<img>显示
            this.courseLogo = reader.result;
          } else {
            this.courseBanner = reader.result;
          }
          // this.form.courseimgUrl = reader.result; // 带前缀的完整Base64，可直接用于<img>显示
          // 方法2：如果需要纯Base64（去掉前缀）
          const pureBase64 = reader.result.split(',')[1];
          this.base64Data = pureBase64;

          // console.log('完整DataURL:', reader.result);
          // console.log('纯Base64:', pureBase64);

          resolve(true); // 必须返回true才会继续上传
          this.customUpload(type)
        };
        reader.onerror = error => {
          console.error('文件读取失败:', error);
          reject(error);
        };
      });
    },


    changeavart(file){
      console.log('头像：',file);
      this.beforeUpload(file.raw,'logo')
    },
    handleAvatarSuccess(res, file) {
      this.courseLogo = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      console.log('上传格式：',file);
      const isJPG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },

    //头像结束
    // banner
    changeBanner(file) {
      console.log('banner：',file);
      this.beforeUpload(file.raw,'banner')
    },


    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
    },


    // 审核不通过
    reviewUnBy(flowid){
      console.log('驳回-1：',flowid);
      regjguserfail({
        "flowid": flowid,
        "flowmsg": this.unReview,
      }).then(res => {
        console.log('驳回：',res,this.unReview);
        this.editFormVisible = false
      })
    },
    resetForm() {
      this.$refs.baseForm.resetFields();
      this.form.businessStatus = '营业中';
      this.form.logoUrl = '';
    },
  }
}
</script>

<style scoped>
.form-container {
  max-width: 800px;
  margin: 20px auto;
}

.head-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 30px;
}

.card-select {
  padding-left: 40px;
  font-size: 14px;
  margin-bottom: 30px;

}

.form-title {
  font-size: 18px;
  font-weight: bold;
}

.required-item >>> .el-form-item__label:before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}
</style>
